package com.gblfy.httpclinet.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    private static Logger logger = LogManager.getLogger(SpringContextUtils.class);

    /**
     * 获取applicationContext对象
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据bean的id来查找对象
     *
     * @param id
     * @return
     */
    public static Object getBeanById(String id) {
        if (applicationContext == null) {
            logger.error("未加载SpringContextUtils,如果是本地Main函数中Test,请在Main函数的Spring文件加载上,添加classpath*:/spring/root-context.xml,具体sample,可参看MemPubSubmitTest");
            return null;
        }
        return applicationContext.getBean(id);
    }

    /**
     * 根据bean的class来查找对象
     *
     * @param c
     * @return
     */
    public static <T> T getBeanByClass(Class<T> c) {
        if (applicationContext == null) {
            logger.error("未加载SpringContextUtils,如果是本地Main函数中Test,请在Main函数的Spring文件加载上,添加classpath*:/spring/root-context.xml,具体sample,可参看MemPubSubmitTest");
            return null;
        }
        return (T) applicationContext.getBean(c);
    }

    /**
     * 根据bean的class来查找所有的对象(包括子类)
     *
     * @param c
     * @return
     */
    public static Map getBeansByClass(Class c) {
        if (applicationContext == null) {
            logger.error("未加载SpringContextUtils,如果是本地Main函数中Test,请在Main函数的Spring文件加载上,添加classpath*:/spring/root-context.xml,具体sample,可参看MemPubSubmitTest");
            return null;
        }
        return applicationContext.getBeansOfType(c);
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
